package com.kaf.api.controller;

import com.kaf.ai.dto.AiRequest;
import com.kaf.ai.dto.AiResponse;
import com.kaf.ai.service.factory.AiServiceFactory;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Map;

@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {

    private final AiServiceFactory aiServiceFactory;

    @PostMapping("/generate")
    public Mono<AiResponse> generate(@Valid @RequestBody AiRequest request) {
        return aiServiceFactory.getAiService(request.getProvider())
                .generateResponse(request);
    }


    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat(@RequestBody AiRequest request) {
        Map<String, Object> body = buildRequestBody(request); // 你的构建逻辑

        return aiServiceFactory.getAiService(request.getProvider()).streamCompletion(body)
                .map(content -> ServerSentEvent.<String>builder()
                        .event("message")
                        .data(content)
                        .build())
                .onErrorResume(e -> Flux.just(ServerSentEvent.<String>builder()
                        .event("error")
                        .data("AI 流式调用失败: " + e.getMessage())
                        .build()));
    }

    private Map<String, Object> buildRequestBody(AiRequest request) {
        // 构建标准 OpenAI 格式
        return Map.of(
                "model", "deepseek-chat",
                "messages", request.getMessages(),
                "temperature", 0.7
        );
    }



}